<template>
  <div class="upload-container">
    <el-upload :multiple="limit > 1" :on-exceed='onExceed' :action="upladUrl" list-type="picture-card" :file-list="fileList" :limit="limit"
      :before-upload="beforeUpload" :on-success="handleSuccess" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  model: {
    prop: 'value',
    event: 'onUpdate'
  },
  name: 'myUpload',
  props: {
    // 单张'xxxxx.jpg' 多张['xxx..jpg', 'xxx..jpg']
    value: {
      type: [String, Array],
      default: ''
    },
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      fileList: []
    }
  },
  mounted() {
    this.init()
  },
  watch: {
    value(value) {
      if (!value) {
        this.fileList = []
      } else {
        if (typeof this.value === 'string') {
            this.fileList = [
              {
                url: this.value
              }
            ]
          } else if (typeof this.value === 'object') {
            this.fileList = []
            this.value.forEach(it => {
              this.fileList.push({
                url: it
              })
            })
          }
      }
    }
  },
  methods: {
    init() {
      this.generateFileList()
    },
    // 根据父类传值，生成图片集合， 单张图片，多张图片 不同处理
    generateFileList() {
      if (!this.value) {
        return (this.fileList = [])
      }
      if (typeof this.value === 'string') {
        this.fileList = [
          {
            url: this.value
          }
        ]
      } else if (typeof this.value === 'object') {
        this.value.forEach(it => {
          this.fileList.push({
            url: it
          })
        })
      }
    },
    handleRemove(file, fileList) {
      this.updateProp(fileList)
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeUpload(file) {
      const isImage = file.type.split('/')[0] === 'image'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('请上传正确图片文件!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    handleSuccess(response, file, fileList) {
      this.updateProp(fileList)
    },
    // 上传超出
    onExceed() {
      return this.$message.error(`最多上传${this.limit}张照片`)
    },
    // 双向绑定同步更新父类图片数据
    updateProp(fileList) {
      let arr = []
      if (fileList.length > 0) {
        fileList.forEach(it => {
          if (it.status === 'success') {
            // 组建上传， 父类传值,取值有所区别
            if (it.response) {
              arr.push(it.response.filePath)
            } else {
              arr.push(it.url)
            }
          }
        })
      }
      if (this.limit === 1) {
        arr = arr[0]
      }
      this.fileList = fileList
      this.$emit('onUpdate', arr)
    }
  }
}
</script>
<style lang="scss" scoped>
.upload-container {
  display: flex;
  width: 100%;
  & > div {
    display: flex;
    width: 100%;
  }
}
/deep/ .el-upload {
  width: 148px;
  height: 148px;
}
</style>
